package com.google.googlemarket.fragement;

import android.view.View;
import android.widget.ListView;

import com.google.googlemarket.R;
import com.google.googlemarket.adapter.CategoryAdapter;
import com.google.googlemarket.adapter.SubjectAdapter;
import com.google.googlemarket.base.BaseFragment;
import com.google.googlemarket.bean.CategoryInfo;
import com.google.googlemarket.http.Urls;
import com.google.googlemarket.utils.JsonUtil;
import com.google.googlemarket.utils.Logger;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;

/**
 * Created by MrGao on 2017/9/17.
 */

public class CategaryFragment extends BaseFragment {

    public static final int TYPE_INIT_DATA = 0;
    public static final int TYPE_INIT_LOADMORE = 1;
    private static final int SWITCH_PAGE = 0;

    private ListView mListView;
    private CategoryAdapter categoryAdapter;

    @Override
    public CharSequence getTitle() {
        return "分类";
    }

    @Override
    public void initView() {
        mListView = findView(R.id.list_view_category);
        categoryAdapter = new CategoryAdapter(null);
        mListView.setAdapter(categoryAdapter);
    }

    @Override
    public void initListener() {
/*
        mListView.setOnLoadingMoreListener(new OnloadingMoreListener() {
            @Override
            public void onLoadingMore() {
                Logger.i("LoadMore","加载更多");
                requestAsyncTask(TYPE_INIT_LOADMORE);
            }

            @Override
            public void onClickRetry() {
                Logger.i("LoadMore","点击重试");
                requestAsyncTask(TYPE_INIT_LOADMORE);
            }
        });*/
    }

    @Override
    public void initData() {
        requestAsyncTask(1);
    }

    @Override
    public int getContentViewLayoutId() {
        return R.layout.fragment_category;
    }

    @Override
    public View getContentView() {
        return null;
    }

    @Override
    protected Object doInBackground(int type) {
        String json = NetUtils.getJson(Urls.CATEGORY, null);
        return json;
    }

    @Override
    protected void onPostExecute(int requestType,Object result) {
        //这里应该加入判断，防止服务器响应返回数据异常为空导致程序崩溃，预设添加一个数据异常提示
        Logger.i(this, "result:" + result);
        String json = (String) result;
      Type type = new TypeToken<ArrayList<CategoryInfo>>() {
        }.getType();
        ArrayList<CategoryInfo> datas = JsonUtil.json2Bean(json, type);
        if (checkInitData(datas)){
            showDatas(datas);
        }
    }

    private void showDatas(ArrayList<CategoryInfo> categaryInfo) {
        Logger.i(this,"datas:"+categaryInfo);
        ArrayList<Object> newDatas = new ArrayList<Object>();
        for (CategoryInfo cateInfo : categaryInfo) {
            newDatas.add(cateInfo.title);
            newDatas.addAll(cateInfo.infos);
        }
        categoryAdapter.getDatas().addAll(newDatas);
        categoryAdapter.notifyDataSetChanged();
    }
}
